package com.activemq.tx;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.activemq.MqHelloWorld;
import lombok.extern.slf4j.Slf4j;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.springframework.boot.autoconfigure.jms.JmsProperties;

import javax.jms.*;
import java.util.Objects;

/**
 * MQ的事务
 *
 * @author wangwy16
 */
@Slf4j
public class TxSender {
    public static void main(String[] args) throws Exception {
        Connection connection = null;
        Session session = null;
        MessageProducer producer = null;
        try {
            ConnectionFactory factory = new ActiveMQConnectionFactory(MqHelloWorld.URL);
            connection = factory.createConnection();
            connection.start();
            //写了true,ack级别基本没用了
            session = connection.createSession(true, JmsProperties.AcknowledgeMode.AUTO.getMode());
            Queue queue = session.createQueue(MqTx.TX_QUEUE);
            producer = session.createProducer(queue);
            for (int i = 0; i < 10; i++) {
                producer.send(session.createTextMessage("测试消息:" + IdUtil.getSnowflakeNextIdStr() + "-" + DateUtil.date().toTimeStr()));
            }
            //需要执行提交方法，session关闭之前要提交
            session.commit();
        } catch (Exception e) {
            log.error("出错", e);
            //出错就回滚
            if (Objects.nonNull(session)) {
                session.rollback();
            }
        } finally {
            if (Objects.nonNull(producer)) {
                producer.close();
            }
            if (Objects.nonNull(session)) {
                session.close();
            }
            if (Objects.nonNull(connection)) {
                connection.close();
            }
        }
    }
}